package com.guosheng.json;

import com.alibaba.fastjson.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.util.*;

public class JsonTestTwo {

    public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if(jsonStr != null && !"".equals(jsonStr)){
            //最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                //如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                   List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        JSONObject json2 = it.next();
                        list.add(json2Map(json2.toString()));
                    }
                    map.put(k.toString(), list);
                    continue;
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        }else{
            return null;
        }
    }

    public static void main(String[] args){
        Map<String,Object> test1 = new HashMap<>();
        test1.put("one",Arrays.asList(1,2,3,4,5,6,7,8));
        JsonEntityTest jet = new JsonEntityTest();
        jet.setAge(18);
        jet.setName("guoshengceshi");
        jet.setPrice(18.8);
        jet.setProducts(Arrays.asList("shen diao xia lv","tian long ba bu","duo qing jian ke wu qing jian"));
        test1.put("two",jet);
        test1.put("three",3);
        test1.put("four","mei you wen ti");
        String json = JSON.toJSONString(test1);

        Map<String,Object> test2 = new HashMap<>();
        test2 = JsonTestTwo.json2Map(json);
        System.out.println(test2);
    }
}
